package com.pethospital.service.impl;

import com.pethospital.service.AIService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI助手服务实现类
 */
@Service
@Slf4j
public class AIServiceImpl implements AIService {

    @Value("${bailian.api-key}")
    private String apiKey;

    @Value("${bailian.access-key-id}")
    private String accessKeyId;

    @Value("${bailian.access-key-secret}")
    private String accessKeySecret;

    private static final String BAILIAN_API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public String chat(String question) {
        log.info("接收到AI助手请求，问题：{}", question);
        
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            
            Map<String, Object> requestBody = new HashMap<>();
            Map<String, Object> input = new HashMap<>();
            
            input.put("prompt", "你是一个宠物健康专家，请针对以下问题提供专业的建议和解答:\n" + question);
            requestBody.put("model", "qwen-turbo");
            requestBody.put("input", input);
            
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("temperature", 0.7);
            parameters.put("max_tokens", 1500);
            parameters.put("result_format", "text");
            requestBody.put("parameters", parameters);

            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
            log.info("发送请求到AI服务: {}", requestBody);

            ResponseEntity<Map> response = restTemplate.postForEntity(BAILIAN_API_URL, requestEntity, Map.class);
            log.info("AI助手响应状态：{}", response.getStatusCode());

            Map<String, Object> responseBody = response.getBody();
            log.info("AI助手响应内容：{}", responseBody);
            
            if (responseBody != null && responseBody.containsKey("output")) {
                Map<String, Object> output = (Map<String, Object>) responseBody.get("output");
                if (output.containsKey("text")) {
                    String result = (String) output.get("text");
                    log.info("AI助手回答：{}", result);
                    return result;
                }
            }

            log.error("AI助手响应格式异常: {}", responseBody);
            return "很抱歉，AI助手暂时无法回答您的问题，请稍后再试。";

        } catch (Exception e) {
            log.error("AI助手请求发生异常", e);
            return "很抱歉，AI助手服务暂时不可用，请稍后再试。";
        }
    }
} 